import Vue from 'vue'
import axios from 'axios'
import qs from 'qs'
import notification from 'ant-design-vue/es/notification'
import store from '../store'
import router from '../router'

// 创建 axios 实例
const service = axios.create({
    baseURL: '/api', // api base_url
    //timeout: 6000 // 请求超时时间
})

const err = (error) => {
    if (error.response) {
        const data = error.response.data
        const token = Vue.ls.get("authtoken")
        if (error.response.status === 403) {
            notification.error({
                message: '没有权限访问！',
                description: data.message
            })
        }
        if (error.response.status === 401 && !(data.result && data.result.isLogin)) {
            notification.error({
                message: '权限不足',
                description: '请您重新登陆！'
            })
            if (token) {
                store.getters.logout.then(() => {
                    window.location.reload()
                })
            }
        }
    }
    return Promise.reject(error)
}

// request interceptor
service.interceptors.request.use(config => {
    if (config.type == 'formData' || config.method != 'post' || config.data instanceof Array) {
        return config
    }
    config.data = qs.stringify(config.data)
    return config
}, err)

// response interceptor
service.interceptors.response.use((response) => {
    let res = response.data
    if(res){
        if(res.code != 0){
            if(res.code == 403){
                notification.error({
                    message: res.msg,
                    description: '错误码：' + res.code
                })
                router.push({ name: 'Login' })
            }
        }
    }
    return response.data
}, err)


export default service
